import {defineStore} from 'pinia'
import {ref, computed} from "vue";
import {getUserInfoApi, logoutApi} from "@/api/auth/index.ts"
import { optimizedRequest } from '@/utils/performance'

export const useUserAuthStore = defineStore('userAuthStore', () => {
        // 定义 store 中的状态
        const token = ref();
        // 姓名
        const name = ref();
        // 用户id
        const userId = ref();
        // 权限值
        const permissions = ref([]);

        // 设置token
        const setToken = (tokenData: string) => {
            token.value = tokenData;
        };

        // 清理数据
        const clearAuthInfo = () => {
            token.value = '';
            name.value = '';
            userId.value = '';
            permissions.value = [];
            
            // 🔥 修复：彻底清理sessionStorage中的认证信息
            sessionStorage.removeItem('userAuth');
        }

        // 退出登陆
        const logout = async () => {
            try {
                await logoutApi();
            } catch (error) {
                console.error('退出登录API调用失败:', error)
            }
            
            // 清理用户认证数据
            clearAuthInfo();
            
            // 🔥 修复：清理菜单状态，确保下次登录重新加载菜单
            const { useMenuStore } = await import('@/store/modules/menu')
            const menuStore = useMenuStore()
            menuStore.$reset()
            
            // 重定向到登录页
            window.location.href = '/login';
        };

        // 🔥 优化点11: 使用缓存和重试机制优化用户信息获取
        const getUserInfo = () => {
            return new Promise((resolve, reject) => {
                optimizedRequest(
                    getUserInfoApi,
                    `userInfo_${userId.value}`, // 缓存键
                    true // 启用缓存
                ).then((res: any) => {
                    name.value = res.data.name;
                    userId.value = res.data.userId;
                    permissions.value = res.data.permissions;
                    resolve(res);
                }).catch((error) => {
                    console.error('获取用户信息失败:', error);
                    reject(error);
                });
            });
        };

        return {userId, name, permissions, token, setToken, getUserInfo, logout, clearAuthInfo};
    },
    {
        persist: {
            key: 'userAuth',
            storage: sessionStorage, // 🔥 修复：使用sessionStorage，浏览器关闭后自动清理
            pick: ['token', 'userId'] // 仅缓存 token 和 userId
        },
    });
